from time import time
from flask import request
from loguru import logger


def register_request_logging(app):
    """注册请求日志钩子"""

    @app.before_request
    def log_request_start():
        request.start_time = time()

    @app.after_request
    def log_request_end(response):
        duration = (time() - request.start_time) * 1000
        logger.info(
            "[{method}] {path} | Status: {status} | Duration: {duration:.2f}ms",
            method=request.method,
            path=request.path,
            status=response.status_code,
            duration=duration,
        )
        return response
